//
//  SubjectSecondViewController.m
//  ITrip
//
//  Created by dllo on 15/5/25.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SubjectSecondViewController.h"
#import "Database.h"
#import "UMSocial.h"
@interface SubjectSecondViewController ()<UMSocialUIDelegate, UIAlertViewDelegate>

@property(nonatomic, retain) UIButton *shareBtn;

@property(nonatomic, retain) UIButton *collectBtn;

@end

@implementation SubjectSecondViewController

- (void) dealloc{
    [_dataArray release];
    [_secondParser release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    

    // 定义菊花控件
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:activityIndicator];
    activityIndicator.color = [UIColor grayColor];
    activityIndicator.center = self.view.center;
    [activityIndicator release];
    [activityIndicator startAnimating];
    

//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"分享" style:UIBarButtonItemStyleDone target:self action:@selector(shareAndCollect)];
    self.shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [self.shareBtn setTitle:@"分享" forState:UIControlStateNormal];
    [self.shareBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [self.collectBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.collectBtn setTitle:@"收藏" forState:UIControlStateNormal];
    
    self.shareBtn.frame = CGRectMake(self.view.frame.size.width - 50, -30, 30, 30);
    self.collectBtn.frame = CGRectMake(self.view.frame.size.width - 50, -30, 30, 30);
    
    
    self.shareBtn.backgroundColor = [UIColor grayColor];
    self.collectBtn.backgroundColor = [UIColor grayColor];
    
    [self.shareBtn addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    [self.collectBtn addTarget:self action:@selector(collect) forControlEvents:UIControlEventTouchUpInside];
    
    
//    [self.view addSubview:self.shareBtn];
//    [self.view addSubview:self.collectBtn];

    
    
    

    //返回按钮
    UIImage *icon = [UIImage imageNamed:@"iconfont_return"];
    icon = [icon imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStyleDone target:self action:@selector(getBack)];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
    [self.navigationItem.leftBarButtonItem release];

    //更改nav透明度
//
//    self.navigationController.navigationBarHidden = YES;
    
    
    
    

    //网络请求
    NSString *path = [URLPath subjectSecondURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *str = [path stringByAppendingFormat:@"%ld.json?page=1", self.number];
    ///不知道什么意思
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        
        self.secondParser = [[SubjectSecondParser alloc] init];
        
        self.dataArray = [self.secondParser getParser:data];
        [self.secondParser release];
        [self createTableView];
        [activityIndicator stopAnimating];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
        [alert show];
        [activityIndicator stopAnimating];
    }];
}






// 网络连接失败

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    // 定义菊花控件
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:activityIndicator];
    activityIndicator.color = [UIColor grayColor];
    activityIndicator.center = self.view.center;
    [activityIndicator release];
    [activityIndicator startAnimating];
    
    //网络请求
    NSString *path = [URLPath subjectSecondURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *str = [path stringByAppendingFormat:@"%ld.json?page=1", self.number];
    ///不知道什么意思
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        
        self.secondParser = [[SubjectSecondParser alloc] init];
        
        self.dataArray = [self.secondParser getParser:data];
        [self.secondParser release];
        [self createTableView];
        [activityIndicator stopAnimating];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
        alert.delegate = self;
        [alert show];
        [activityIndicator stopAnimating];
    }];
}

#pragma -mark share
- (void)shareAndCollect
{
    [UIView animateWithDuration:0.5 animations:^{
        self.shareBtn.frame = CGRectMake(self.view.frame.size.width - 50, 0, 40, 40);
        self.collectBtn.frame = CGRectMake(self.view.frame.size.width - 50, 40, 40, 40);
        self.shareBtn.layer.cornerRadius = 20;
        self.shareBtn.layer.masksToBounds = YES;
        self.collectBtn.layer.cornerRadius = 20;
        self.collectBtn.layer.masksToBounds = YES;
    }];
    [self.view bringSubviewToFront:self.shareBtn];
    [self.view bringSubviewToFront:self.collectBtn];
}

- (void)share
{
    [UIView animateWithDuration:0.5 animations:^{
        self.shareBtn.frame = CGRectMake(self.view.frame.size.width - 50, -40, 40, 40);
        self.collectBtn.frame = CGRectMake(self.view.frame.size.width - 50, -40, 40, 40);
    }];
    
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.secondParser.image_url] options:NSDataReadingMappedAlways error:nil];
    UIImage *image = [UIImage imageWithData:data];
    NSString *share = self.secondParser.name;
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5569046f67e58e40e6002b92"
                                      shareText:share
                                     shareImage:image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,nil]
                                       delegate:self];
}
- (void)collect
{
    [UIView animateWithDuration:0.5 animations:^{
        self.shareBtn.frame = CGRectMake(self.view.frame.size.width - 50, -40, 40, 40);
        self.collectBtn.frame = CGRectMake(self.view.frame.size.width - 50, -40, 40, 40);
    }];
    NSArray *array = [Database selectData];
    int i = 0;
    for (DbModel *model in array) {
        if (model.titleId == self.number) {
            i = 1;
            break;
        }
    }
    if (i == 1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您已经收藏过了!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
        [alert show];
    } else {
        DbModel *model = [DbModel getDbModel];
        model.title = self.secondParser.name;
        model.titleId = self.number;
        model.choose = 1;
        [Database insertValue:model];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"收藏成功!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
        [alert show];
    }
    
    
}

- (void) viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBar.translucent = NO;
    if (self.isTopic != 1) {
        self.tabBarController.tabBar.hidden = NO;
        self.tabBarController.tabBar.translucent = NO;
        
    }
}


- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.translucent = YES;
    self.tabBarController.tabBar.hidden = YES;
    self.tabBarController.tabBar.translucent = YES;
}

- (void)getBack
{

    //改变回原来的导航颜色
    
    self.navigationController.navigationBar.translucent = NO;
    if (self.isTopic != 1) {
        self.tabBarController.tabBar.hidden = NO;
        self.tabBarController.tabBar.translucent = NO;
        
    }

//    NSLog(@"%ld", self.isTopic);
       [self.navigationController popViewControllerAnimated:YES];
}

///创建TableView
-(void)createTableView
{
    tView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:tView];
    
    tView.dataSource = self;
    
    tView.delegate = self;
    [tView release];
    ///定义headView
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 160)];
    ///定义headView图片
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, headView.frame.size.width, headView.frame.size.height)];
    imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight| UIViewAutoresizingFlexibleWidth;
    imageView.clipsToBounds = YES;
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    [imageView setImageWithURL:[NSURL URLWithString:self.secondParser.image_url]];
    

    
    
    ///定义旅行地名
    UILabel *tripName = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, headView.frame.size.width, 40)];
    tripName.text = self.secondParser.name;
    tripName.font = [UIFont systemFontOfSize:32];
    tripName.textColor = [UIColor whiteColor];
    tripName.center = headView.center;
    tripName.textAlignment = NSTextAlignmentCenter;
    
    ///定义标题名
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, tripName.frame.origin.y + tripName.frame.size.height + 10, headView.frame.size.width - 40, 30)];
    titleLabel.text = self.secondParser.title;
    titleLabel.font = [UIFont systemFontOfSize:20];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    
    
    [headView addSubview:imageView];
    [headView addSubview:tripName];
    [headView addSubview:titleLabel];
    _header = [CExpandHeader expandWithScrollView:tView expandView:headView];
//    tView.tableHeaderView = headView;
//    [headView release];
//    [imageView release];
//    [tripName release];
//    [titleLabel release];
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;

}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *identifier = @"cell";
    SubjectSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[[SubjectSecondTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];
        cell.contentView.frame = CGRectMake(cell.frame.origin.x, cell.frame.origin.y, self.view.frame.size.width, cell.frame.size.height);
    }
    
    cell.titleLabel.text = nil;
    cell.imageTitleLabel.text = nil;
    cell.imageView_.image = nil;
    cell.descriptionLabel.text = nil;
    cell.nameLabel.text = nil;
    cell.titleIcon.image = nil;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    SubjectSecondModel *secondModel = [self.dataArray objectAtIndex:indexPath.row];
//    [cell setSubjectSecondModel:secondModel];

    SubjectSecondModel *secondModel = [SubjectSecondModel getModel];
    if (self.dataArray.count > indexPath.row && indexPath.row >= 0) {
        secondModel= [self.dataArray objectAtIndex:indexPath.row];
    }
    [cell setSubjectSecondModel:secondModel];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

///cell高度
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SubjectSecondModel *subjectSecondModel = [self.dataArray objectAtIndex:indexPath.row];

    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:15] forKey:NSFontAttributeName];
    CGRect frame;
    if (subjectSecondModel.descriptions != nil && subjectSecondModel.descriptions.length != 0) {
        frame = [subjectSecondModel.descriptions boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 20, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    }
    
    // 1.无标题
    if (subjectSecondModel.title == nil
         || subjectSecondModel.title.length == 0) {
        // 2.无图片
        if (subjectSecondModel.image_url == nil || subjectSecondModel.image_url.length == 0) {
            // 3.无文字
            if (subjectSecondModel.descriptions == nil || subjectSecondModel.descriptions.length == 0) {
                return 0;
            // 3.有文字
            } else if (subjectSecondModel.descriptions != nil && subjectSecondModel.descriptions.length != 0) {
//                NSLog(@"%f", frame.size.height);
            ///return文字高度
                return frame.size.height + 20;
            }
            
        // 2.有图片
        } else if (subjectSecondModel.image_url != nil && subjectSecondModel.image_url.length != 0) {
            
            // 3.无文字
            if (subjectSecondModel.descriptions == nil || subjectSecondModel.descriptions.length == 0) {
                /// return图片高度
                return (self.view.frame.size.width - 20) * (subjectSecondModel.image_height  / (CGFloat)subjectSecondModel.image_width) + 20;
                // 3.有文字
            } else if (subjectSecondModel.descriptions != nil && subjectSecondModel.descriptions.length != 0) {
                
                ///return 图片+文字高度
                return (self.view.frame.size.width - 20) * (subjectSecondModel.image_height  / (CGFloat)subjectSecondModel.image_width) + frame.size.height + 30;
            }
        
        }
    
 
     
    //1.有标题
    }else if (subjectSecondModel.title != nil && subjectSecondModel.title.length != 0) {
        
    
        // 2.无图片
        if (subjectSecondModel.image_url == nil || subjectSecondModel.image_url.length == 0) {
            // 3.无文字
            if (subjectSecondModel.descriptions == nil || subjectSecondModel.descriptions.length == 0) {
              ///  return 标题高度;
                return 40;
                // 3.有文字
            } else if (subjectSecondModel.descriptions != nil && subjectSecondModel.descriptions.length != 0) {
                
                ///return 标题+文字高度
                return frame.size.height + 55;
            }
            
            // 2.有图片
        } else if (subjectSecondModel.image_url != nil && subjectSecondModel.image_url.length != 0) {
            
            // 3.无文字
            if (subjectSecondModel.descriptions == nil || subjectSecondModel.descriptions.length == 0) {
                /// return 标题+图片高度
                return (self.view.frame.size.width - 20) * (subjectSecondModel.image_height  / (CGFloat)subjectSecondModel.image_width) + 40;
                // 3.有文字
            } else if (subjectSecondModel.descriptions != nil && subjectSecondModel.descriptions.length != 0) {
                
                ///return 标题+图片+文字高度
                return (self.view.frame.size.width - 20) * (subjectSecondModel.image_height  / (CGFloat)subjectSecondModel.image_width) + frame.size.height + 40;
                

            }
            
        }

    }
    return 0;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
